<template>
  <div class="assign">
    <div
      :class="['selecSate', isAutoAssign === 'self' ? 'selecSate-self' : '']"
    >
      <div class="selec">
        <div class="input-group">
          <span class="self-label">{{
            isAutoAssign !== 'self' ? $t('public.pickAgent') + ':' : '提醒座席'
          }}</span>
          <agent-tree-select
            ref="agentTree"
            class="agent-tree"
            :moudule="moudule"
            :checkedAgentsOfChannelConfigTree="checkedAgentsOfChannelConfig"
            :agentCheckedIds="agentCheckedIds"
            :forChannelConfig="forChannelConfig"
            :PBX="PBX"
            @agent-change="handleAgentChange"
          >
          </agent-tree-select>
        </div>
        <div class="input-group" style="flex: 1" v-if="openBatch">
          <!-- <span class="self-label">{{ $t('public.batchAdd') + ':' }}</span> -->
          <AgentBatchAdd ref="agentBatchAdd" :agents="agentsList" @change="batchAddChange">
          </AgentBatchAdd>
        </div>
        <div class="btn-group" v-if="!forChannelConfig">
          <div class="default" v-if="isAutoAssign !== 'self'">
            <span class="auto" @click.stop="autoAssign">{{
              $t('public.autoAssign')
            }}</span>
            <span class="rest" @click.stop="reset">{{
              $t('public.reset')
            }}</span>
          </div>
          <slot name="self" v-else> </slot>
        </div>
      </div>
      <div class="scResult aaa" :class="{ minHei: forChannelConfig }">
        <span class="count" v-if="checkedAgents.length === 0">{{
          $t('public.noAgent')
        }}</span>
        <div class="resu" v-if="checkedAgents.length !== 0">
          <p>
            {{
              $t('public.hasPickAgentWithCount', {
                count: checkedAgents.length
              })
            }}
            <span class="fr clea" @click="clear">{{ $t('public.clear') }}</span>
          </p>
          <el-row>
            <div v-for="(item, index) in checkedAgents" :key="index" :class="!inputShow ? 'inputNone' : 'result'">
              <span class="agent-name">{{ item.displayName }}</span>
              <el-input
                v-if="isAutoAssign !== 'self' && inputShow"
                size="mini"
                class="an-count"
                v-model.trim="agentCount[item._id]"
                type="number"
                min="0"
                @change="handleAgentCountChange(item._id)"
              >
              </el-input>
              <i class="iconfont icon-guanbi" @click="dele(index)"></i>
            </div>
            <!--<el-col :span="6" v-for="(item, index) in checkedAgents" class="fl result">-->
            <!--<span class="agent-name">{{item.displayName}}</span>-->
            <!--<el-input v-if="isAutoAssign!=='self'" size="mini" class="an-count" v-model.trim="agentCount[item._id]" type="number" min="0" @change="handleAgentCountChange(item._id)">-->
            <!--</el-input>-->
            <!--<i class="iconfont icon-guanbi" @click= "dele(index)"></i>-->
            <!--</el-col>-->
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { deepClone } from '@/utils/m7Utils'
import AgentTreeSelect from '../agent-tree/AgentTreeSelect.vue'
import AgentBatchAdd from '../agent-tree/AgentBatchAdd.vue'
export default {
  name: 'AssignCustomer',
  data () {
    return {
      checkedAgents: [],
      agentCount: {},
      agentCheckedIds: []
    }
  },
  props: {
    count: {
      type: Number,
      default: 0
    },
    moudule: String,
    forChannelConfig: {
      type: Boolean,
      default: false
    },
    inputShow: {
      type: Boolean,
      default: true
    },
    PBX: {
      type: String,
      default: ''
    },
    checkedAgentsOfChannelConfig: {
      type: Array,
      default: function () {
        return []
      }
    },
    isAutoAssign: String,
    openBatch: {
      type: Boolean,
      default: false
    }
  },
  components: {
    AgentTreeSelect,
    AgentBatchAdd
  },
  methods: {
    // 自动分配
    autoAssign () {
      let num = Math.floor(this.count / this.checkedAgents.length)
      for (let key in this.agentCount) {
        this.agentCount[key] = num
      }
      let restCount = this.count - num * this.checkedAgents.length
      for (let key in this.agentCount) {
        if (restCount === 0) {
          break
        }
        this.agentCount[key]++
        restCount--
      }
    },
    // 点击重置时触发
    reset () {
      for (let key in this.agentCount) {
        this.agentCount[key] = 0
      }
    },
    // 清除
    clear () {
      this.checkedAgents = []
      this.agentCount = {}
      this.$emit('resetAgent')
    },
    // 删除
    dele (index) {
      let _id = this.checkedAgents[index]._id
      this.$emit('deleteAgent', _id)
      this.$set(this.agentCount, _id, 0)
      delete this.agentCount[_id]
      this.checkedAgents.splice(index, 1)
      if (this.checkedAgents.length === 0) {
        this.$emit('resetAgent')
      }
    },
    getAgentMaxCount (id) {
      let count = 0
      for (let key in this.agentCount) {
        if (key !== id) {
          count += parseInt(this.agentCount[key])
        }
      }
      return this.count - count
    },
    handleAgentChange (checkedAgents) {
      this.checkedAgents = checkedAgents
      let ids = checkedAgents.map(agent => agent._id)
      ids.forEach(item => {
        if (!this.agentCount[item]) {
          this.$set(this.agentCount, item, 0)
        }
      })
      let obj = {}    //   清洗agentCount对象
      for (let key in this.agentCount) {
        if (ids.indexOf(key) !== -1) {
          obj[key] = this.agentCount[key]
        }
      }
      this.agentCount = obj
    },
    // 座席分配数量更改
    handleAgentCountChange (id) {
      if (this.agentCount[id] < 0) {
        this.$set(this.agentCount, id, 0)
      }
    },
    resetAgent () {
      this.$refs.agentTree.$emit('resetAgent')
    },
    deleteAgent: function (_id) {
      this.$refs.agentTree.$emit('deleteAgent', _id)
    },
    intQueueConfig: function () {   //  技能组设置  座席回显
      this.agentCount = {}
      let deecloneAgents = deepClone(this.checkedAgentsOfChannelConfig)
      this.agentCheckedIds = deecloneAgents.map(agent => agent._id)
      this.checkedAgents = deecloneAgents
      deecloneAgents.forEach(item => {
        this.$set(this.agentCount, item._id, item.count)
      })
      this.$refs.agentBatchAdd.clear()
    },
    batchAddChange (uniqueList) {
      let agentsList = this.$refs.agentTree.agentsList || []
      let checkAgents = [];
      let unmatchList = [];
      let successCount = uniqueList.length;
      let failCount = 0;
      uniqueList.some((value) => {
        let distinguishFlag = false
        agentsList.some((agent) => {
          if (agent.exten === value) {
            distinguishFlag = true
            checkAgents.push({
              displayName: agent.displayName,
              exten: agent.exten,
              _id: agent._id
            })
            return true
          }
        })
        // 匹配到座席
        if (!distinguishFlag) {
          unmatchList.push(value)
        }
      })
      // 去掉重复匹配座席
      let uniqueAgentList = []
      let uniqueIdList = []
      checkAgents.some((checkAgent) => {
        let flag = false
        this.checkedAgents.some((checkedAgent) => {
          if (checkedAgent._id === checkAgent._id) {
            flag = true
            return true
          }
        })
        if (!flag) {
          uniqueAgentList.push(checkAgent)
          uniqueIdList.push(checkAgent._id)
        }
      })
      this.handleAgentChange([...this.checkedAgents, ...uniqueAgentList])
      this.$refs.agentBatchAdd.setBatchInfo({unmatchList: unmatchList})
    }
  },
  beforeDestroy: function () {
    this.$off('resetAgent', this.resetAgent)
    this.$off('deleteAgent', this.deleteAgent)
  },
  computed: {
    restCount () {
      return this.count - this.assignedCount
    },
    assignedCount () {
      let count = 0
      for (let key in this.agentCount) {
        count += parseInt(this.agentCount[key])
      }
      return count
    },
    agentsList () {
      if (this.$refs.agentTree && this.$refs.agentTree.agentsList) {
        return this.$refs.agentTree.agentsList
      } else {
        return []
      }
    }
  },
  watch: {
    assignedCount () {
      let agents = []
      for (let key in this.agentCount) {
        if (this.forChannelConfig) {
          agents.push({ agent: key, count: parseInt(this.agentCount[key]) || 0 })
        } else {
          if (this.agentCount[key]) {
            agents.push({ agent: key, count: parseInt(this.agentCount[key]) })
          }
        }
      }
      this.$emit('assign-change', agents)
    },
    checkedAgents () {
      if (this.forChannelConfig) {
        let agents = []
        for (let key in this.agentCount) {
          agents.push({ agent: key, count: parseInt(this.agentCount[key]) || 0 })
        }
        this.agentCheckedIds = agents.map(agent => agent.agent)
        this.$emit('assign-change', agents)
      }
    },
    checkedAgentsOfChannelConfig () {
      this.intQueueConfig()   //  技能组设置  座席回显
    }
  },
  beforeMount () {
    this.$on('resetAgent', this.resetAgent)
    this.$on('deleteAgent', this.deleteAgent)
    if (this.checkedAgentsOfChannelConfig.length > 0) {
      this.intQueueConfig()
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '../../../assets/common'
.assign
  .selecSate
    padding 0 12px 0 16px
    .scResult
      border-top 1px solid $c-border1
      padding-top 16px
      padding-left 16px
      margin-top 10px
      min-height 248px
      .count
        color $cf-gray4
      .resu
        p
        color $cf-gray1
      .el-row
        height 210px
        font-size 12px
        margin-top 1em
        overflow-y auto
      .inputNone
        display inline-block
        align-items center
        margin-bottom 1em
        margin-right 15px
        .agent-name
          display inline-block
          color $cf-gray1
          padding-right 7px
        .icon-guanbi
          font-size 12px
          color $cf-gray5
          margin-left 10px
          cursor pointer
      .result
        float left
        display flex
        align-items center
        margin-bottom 1em
        margin-right 15px
        .agent-name
          display inline-block
          color $cf-gray1
          padding-right 7px
        .el-input
          width 60px
          height 24px
        .icon-guanbi
          font-size 12px
          color $cf-gray5
          margin-left 10px
          cursor pointer
      .clea
        cursor pointer
      .resu
        p
          height 20px
          line-height 20px
          span
            color $c-main
      ul
        li
          margin 10px 30px 0 0
          font-size 12px
          color #b8b8b8
          .iconfont
            font-size 14px
          input
            width 56px
            font-size 12px
            padding 5px 10px
    .selec
      color $cf-gray1
      display flex
      align-items center
      justify-content space-between
      .agent-tree
        width 216px
        display inline-block
      .auto
        margin-right 14px
      .auto, .rest
        cursor pointer
        color $c-main
    .minHei
      min-height 200px
.assign
  .selecSate-self
    padding 0
.self-label
  display block
  padding-bottom 8px
</style>
